import turbogears as tg
from turbogears import controllers, expose, flash
from turbogears.widgets import DataGrid
from bookloantracker.model import *
import logging
log = logging.getLogger("bookloantracker.controllers")
import datetime

from bookcadaster import BookCadaster
from author import AuthorCadaster
from publisher import PublisherCadaster
from loaner import LoanerCadaster
from loan import LoanEngine

bookIndex = DataGrid(
    template="""<div xmlns:py="http://purl.org/kid/ns#">
  <script>
  confirmAndCall=function(url) {
    if (confirm('Return book?')) {
        this.location = url;
    }
  }
  </script>
  <table id="${name}" class="grid" cellpadding="0" cellspacing="1" border="0">
    <thead py:if="columns">
      <tr>
          <th py:for="i, col in enumerate(columns)" class="col_${i}">
            ${col.title}
          </th>
          <th>&nbsp;</th>
      </tr>
    </thead>
    <tr py:for="i, row in enumerate(value)" class="${i%2 and 'odd' or 'even'}">
      <td py:for="col in columns">
        <spam py:if="col.name != 'column-0'">${col.get_field(row)}</spam>
        <a href="${tg.url('/books/info?id=%s' % row.id)}" py:if="col.name == 'column-0'">${col.get_field(row)}</a>
      </td>
      <td width="80">
        <a href="/loan?id=${row.id}" py:if="not row.isLoaned">Loan</a>
        <a href="#" onclick="confirmAndCall('/loan/returnBook?id=${row.id}')" py:if="row.isLoaned">Return</a>
      </td>
    </tr>
  </table>
</div>
""",
    fields = [(_("Book"),"title"),
              (_("Author"),"authorStr"),
              (_("Publisher"),lambda book: book.publisher.name),
              (_("Localization"),"localization")]
    )

class Root(controllers.RootController):
    books=BookCadaster()
    authors=AuthorCadaster()
    publishers=PublisherCadaster()
    loaner=LoanerCadaster()
    loan=LoanEngine()

    @expose(template="bookloantracker.templates.bookindex")
    def index(self):
        bookList = Book.select()
        return dict(bookList = bookList,
                    bookIndex = bookIndex)

    @expose()
    def acGetAuthor(self, authorName):
        authors = authorName.split(",")
        authorSearched = authors[-1].strip()
        numberOfAuthors = len(authors)
        alredyTyped = ""
        if numberOfAuthors > 1:
            alredyTyped = ",".join(authors[0:numberOfAuthors-1])
            alredyTyped += ","
        matches=[]
        if not authorSearched:
            return matches
        authorsInDb = Author.select(Author.q.name.startswith(authorSearched))
        for author in authorsInDb:
            matches.append(alredyTyped+author.name)
        log.debug("Returning matches: %s" % matches)
        return dict(matches=matches)

    @expose()
    def acGetPublisher(self, publisherName):
        publisherName = publisherName.strip()
        matches=[]
        publisherInDb = Publisher.select(Publisher.q.name.startswith(publisherName))
        for publisher in publisherInDb:
            matches.append(publisher.name)
        log.debug("Returning matches: %s" % matches)
        return dict(matches=matches)

    @expose()
    def acGetLoaner(self, loanerName):
        loanerName = loanerName.strip()
        matches=[]
        loanerInDb = Loaner.select(Loaner.q.name.startswith(loanerName))
        for loaner in loanerInDb:
            matches.append(loaner.name)
        log.debug("Returning matches: %s" % matches)
        return dict(matches=matches)

    @expose()
    def acGetWordKeys(self, wordKey):
        words = wordKey.split(",")
        wordSearched = words[-1].strip()
        numberOfWords = len(words)
        alredyTyped = ""
        if numberOfWords > 1:
            alredyTyped = ",".join(words[0:numberOfWords-1])
            alredyTyped += ","
        matches = []
        if not wordSearched:
            return matches
        wordsInDb = WordKeys.select(WordKeys.q.word.startswith(wordSearched))
        for word in wordsInDb:
            matches.append(alredyTyped+word.word)
        log.debug("Returning matches: %s" % matches)
        return dict(matches=matches)

